package com.xukehong.demo.util.send;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author: xkh
 * @Date: 2019/8/20 17:04
 * @Version 1.0
 * 发送邮件
 * POP3
 * IMAP
 */
public class SendMailUtil {

    private static final String MAIL_HOST = "smtp.163.com";
    private static final String MAIL_TRANSPORT_PROTOCOL = "smtp";
    //发送方
    private static final String SEND_USER = "a15695916921@163.com";
    //接收方
    private static final String RECEIVE_USER = "1750687108@qq.com";
    // 163邮箱申请的邮件发送密码
    private static final String PASSWORD = "123456788";
    /**
     * 发送邮件
     */
    public static void SendMail(String subject, String content) throws Exception {
        Properties prop = new Properties();
        prop.setProperty("mail.host", MAIL_HOST);
        prop.setProperty("mail.transport.protocol", MAIL_TRANSPORT_PROTOCOL);
        prop.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(prop);
        //开启debug模式，方便看程序发送Email的运行状态
        session.setDebug(true);
        Transport ts = session.getTransport();
        ts.connect(MAIL_HOST, SEND_USER, PASSWORD);
        Message message = simpleMail(session, subject, content);
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }


    /**
     * 一封简单的只包含文本的邮件
     */
    public static MimeMessage simpleMail(Session session, String subject, String content) throws Exception {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(SEND_USER));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("XXXXXX@qq.com"));
        message.setSubject(subject);
        message.setContent(content, "text/html;charset=UTF-8");
        return message;
    }
}
